import express from 'express';
import cors from 'cors';
import fetch from 'node-fetch';

const app = express();
const PORT = 3001;

app.use(cors());
app.use(express.json());

// 代理端点 - 提交视频生成
app.post('/api/generate-video', async (req, res) => {
    try {
        console.log('收到视频生成请求:', req.body);

        const response = await fetch('https://api.siliconflow.cn/v1/video/submit', {
            method: 'POST',
            headers: {
                'Authorization': 'Bearer sk-laazbuiqreiawuymokbyirubefyxfpfovaexzqtjxcuwrhuo',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(req.body)
        });

        if (!response.ok) {
            const errorText = await response.text();
            throw new Error(`API 响应错误: ${response.status} ${response.statusText} - ${errorText}`);
        }

        const data = await response.json();
        console.log('API 响应成功:', data);
        res.json(data);
    } catch (error) {
        console.error('代理服务器错误:', error.message);
        res.status(500).json({
            error: '代理服务器错误',
            details: error.message
        });
    }
});

// 代理端点 - 查询视频状态（修正为 POST 请求）
app.post('/api/status', async (req, res) => {
    try {
        const { requestId } = req.body;

        if (!requestId) {
            return res.status(400).json({ error: '缺少 requestId 参数' });
        }

        console.log('查询视频状态:', requestId);

        const response = await fetch(`https://api.siliconflow.cn/v1/video/status`, {
            method: 'POST',
            headers: {
                'Authorization': 'Bearer sk-laazbuiqreiawuymokbyirubefyxfpfovaexzqtjxcuwrhuo',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ requestId })
        });

        if (!response.ok) {
            const errorText = await response.text();
            throw new Error(`状态查询错误: ${response.status} ${response.statusText} - ${errorText}`);
        }

        const data = await response.json();
        console.log('状态查询结果:', data);
        res.json(data);
    } catch (error) {
        console.error('状态查询错误:', error.message);
        res.status(500).json({ error: error.message });
    }
});

app.listen(PORT, () => {
    console.log(`代理服务器运行在 http://localhost:${PORT}`);
    console.log('API 端点: https://api.siliconflow.cn/v1/video/submit');
});
